home *** CD-ROM | disk | FTP | other *** search
- Path: druid.borland.com!usenet
- From: pete@borland.com (Pete Becker)
- Newsgroups: comp.lang.c++
- Subject: Re: Friend vs. Member function for operator overload
- Date: 11 Apr 1996 21:55:48 GMT
- Organization: Borland International
- Message-ID: <4kjv54$19t@druid.borland.com>
- References: <4kj55n$mv2@homenet.hom.net>
- NNTP-Posting-Host: pbecker.borland.com
- Mime-Version: 1.0
- Content-Type: Text/Plain; charset=ISO-8859-1
- X-Newsreader: WinVN 0.99.5
-
- In article <4kj55n$mv2@homenet.hom.net>, dengel@hom.net says...
- >
- >Can anyone tell me the relative advantages and disadvantages of using
- >a friend function vs. a member function to overload an operator, such
- >as addition? For example, suppose you have a Complex class (I'm not
- >interested in building a complex class--I'm just using this for an
- >example.):
- >
- >class Complex {
- >private:
- > int real, imag;
- >. . .
- >};
- >
- >Now, you would want to be able to add complex numbers, like so:
- >
- >Complex a, b, c;
- >
- >a = (some complex number);
- >b = (some complex number);
- >c = a + b;
- >
- >Now, as far as I can tell, there are two general approaches to this.
- >One is the declare a friend function header in the class definition:
- >
- >friend Complex operator+( Complex& a, Complex& b) ;
- >
- >and then define that function something like:
- >
- >Complex operator+( Complex& const a, Complex& const b) {
- > Complex temp;
- > temp.real = a.real + b.real;
- > temp.imag = a.imag + b.imag;
- > return temp;
- >}
- >
- >The other way is to put the operator in the class definition itself:
- >
- >Complex operator+( Complex& const a) {
- > Complex temp;
- > temp.real = this->real + a.real;
- > temp.imag = this->imag + a.imag;
- > return temp;
- >}
- >
- >Can anyone tell me if one of these the "preferred" way of doing it?
- >And, what are the advantages and disadvantages of each?
-
- The preferred way is to make the usual binary operators globals. That way you
- can write expressions like this:
-
- complex c = 1;
- complex d = 1 + c;
-
- If the + operator were a member there would be no way for the compiler
- to evaluate 1 + c, because 1 is not of type complex. When the function is
- global the compiler can convert it to a complex and use the global operator.
- Further, the global function usually doesn't need to be a friend. Just
- implement it with +=, which should be a member.
- -- Pete
-
-